﻿using System;
using System.Collections.Generic;
using System.Text;
using CSharpHelpers.DateTimes;
using CSharpHelpers.IOs;
using CSharpHelpers.Regexs;

namespace CSharpHelpers.Formats
{
    class DecimalConvertHelper
    {
        /// <summary>
        /// 16进制字符串 转成 byte[]，每连个 字符代表一个16进制值 转为一个 byte
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] HexByteArrayToByteArray(byte[] data)
        {
            var str = Encoding.ASCII.GetString(data);
            var listByte = new List<byte>();
            for (int i = 0; i < (str.Length / 2); i++)
            {
                var hex = Convert.ToInt32(str.Substring(i * 2, 2), 16);
                listByte.Add((byte)hex);
            }

            return listByte.ToArray();
        }

        /// <summary>
        /// byte[]  每一个byte 转为两个字符串的16进制值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] ByteArrayToHexByteArray(byte[] data)
        {
            var sb = new StringBuilder();
            foreach (byte b in data)
            {
                string hexStr = Convert.ToString(b, 16);
                if (hexStr.Length < 2)
                {
                    hexStr = "0" + hexStr;
                }
                sb.Append(hexStr.ToUpper());
            }

            var byteArray = Encoding.ASCII.GetBytes(sb.ToString());
            return byteArray;

        }

        /// <summary>
        ///十六进制转换成十进制
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Byte Get16To10(string str)
        {
            Byte value = new Byte();
            value = Convert.ToByte(Convert.ToInt32(str, 16));
            return value;
        }

        /// <summary>
        /// 转换成整数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int GetIntString(object value)
        {
            int result = 0;
            int.TryParse(value.ToString(), out result);
            return result;
        }

        public static readonly string PASSWORD = "gecp2012";
        public static readonly int VISA_PAGE_COUNT = 10;
        public static readonly int NEWS_COUNT = 10;
        public static readonly int NOTICE_COUNT = 10;

        /// <summary>
        /// 获得字符串长度
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetStrLength(string str)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("[\u4e00-\u9fa5]", System.Text.RegularExpressions.RegexOptions.Compiled);
            char[] stringChar = str.ToCharArray();
            int nLength = 0;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    nLength += 2;
                }
                else if (IsChiSymbol(stringChar[i]))
                {
                    nLength += 2;
                }
                else
                {
                    nLength++;
                }
            }
            return nLength;
        }

        public static string GetSubStr(string str, int len)
        {
            string res = string.Empty;
            char[] strCh = str.ToCharArray();
            for (int i = 0; i < len; i++)
            {
                res += strCh[i];
            }
            return res;
        }

        private static bool IsChiSymbol(char ch)
        {
            bool res = false;
            byte[] bytes = Encoding.Unicode.GetBytes(new char[] { ch });
            if (bytes.Length == 2)
            {
                if (bytes[1] != 0)
                    res = true;
            }
            return res;
        }

        /// <summary>
        /// 字符數組轉字符串
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public static string GetStringByArray(string[] array)
        {
            string res = string.Empty;
            foreach (string str in array)
            {
                res += str + ",";
            }
            res = res.Length > 0 ? res.Substring(0, res.Length - 1) : res;
            return res;
        }

        public static string GetStringByArray(int[] array)
        {
            string res = string.Empty;
            foreach (int num in array)
            {
                res += num + ",";
            }
            res = res.Length > 0 ? res.Substring(0, res.Length - 1) : res;
            return res;
        }

        public static string GetStringByList(List<string> array)
        {
            string res = string.Empty;
            foreach (string num in array)
            {
                res += num + ",";
            }
            res = res.Length > 0 ? res.Substring(0, res.Length - 1) : res;
            return res;
        }


        public static string GetStringByArray(double[] array)
        {
            string res = string.Empty;
            foreach (double num in array)
            {
                res += num + ",";
            }
            res = res.Length > 0 ? res.Substring(0, res.Length - 1) : res;
            return res;
        }


        /// <summary>
        /// 过滤非法sql字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Filterstr(string str)
        {
            string strs = str;
            strs = strs.Replace(",", "");
            strs = strs.Replace("'", "");
            //strs = strs.Replace("and", "");
            //strs = strs.Replace("or", "");
            strs = strs.Replace(";", "");
            return strs;
        }

        /// <summary>
        /// 將obj 轉為 DateTime 如果datetime等於 0001-01-01 無效日期則賦值1900-01-01
        /// @author Bell add by 2013-7-15
        /// </summary>
        /// <param name="obj">被轉的obj</param>
        /// <returns>返回日期</returns>
        private static DateTime CoverToDateTime(object obj)
        {
            DateTime day = new DateTime(1900, 1, 1);
            if (obj != null)
            {
                DateTime.TryParse(obj.ToString(), out day);
            }

            if (day == new DateTime())
            {
                day = new DateTime(1900, 1, 1);
            }

            return day;
        }

        /// <summary>
        /// string -> int
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int ConvertStrToInt(string str)
        {
            int value;
            if (str.Equals("") || !RegexHelper.IsInt(str))
            {
                return -1;
            }

            try
            {
                value = Convert.ToInt32(str);
            }
            catch (Exception ex)
            {
                SystemLog.Error(ex);
                return -1;
            }

            return value;
        }

        /// <summary>
        /// 转换成小数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static double GetDoubleString(object value)
        {
            double result = 0;
            Double.TryParse(value.ToString(), out result);
            return result;
        }

        ///// <summary>
        ///// 转换成整数
        ///// </summary>
        ///// <param name="value"></param>
        ///// <returns></returns>
        //public static int GetIntString(object value)
        //{
        //    int result = 0;
        //    Int32.TryParse(value.ToString(), out result);
        //    return result;
        //}

        /// <summary>
        /// 获取四舍五入保留小数
        /// 默认一位
        /// </summary>
        /// <returns></returns>
        public static double GetSswrDouble(double d, int saveCount = 1)
        {
            var tarD = Math.Round(d, saveCount, MidpointRounding.AwayFromZero);
            return tarD;
        }

        //轉成1,000,000.00
        public static string GetFormatDoubleToString(double val)
        {
            return string.Format("{0:N2}", val);
        }

        //保留四位小數，小數部分末位為零的去掉
        public static string SetDecimal(double dou)
        {
            string temp = dou.ToString("0.0000");
            while (temp.Substring(temp.Length - 1) == "0")
            {
                temp = temp.Remove(temp.Length - 1);
            }
            if (temp.Substring(temp.Length - 1) == ".")
            {
                temp = temp.Remove(temp.Length - 1);
                return temp;
            }
            return temp;
        }

        public static string SetDecimal(double dou, int count)
        {
            return String.Format("{0:N" + count + "}", dou);
        }

        //保留四位小數，小數部分末位為零的去掉,第一位小數的零保留
        public static string SetDecimalLeastOne(double dou)
        {
            string temp = dou.ToString("0.0000");
            while (temp.Substring(temp.Length - 1) == "0")
            {
                temp = temp.Remove(temp.Length - 1);
            }
            if (temp.Substring(temp.Length - 1) == ".")
            {
                return temp + "0";
            }
            return temp;
        }

        public static void GetDateTimeStartAndEnd(DateTime time, out DateTime timeStart, out DateTime timeEnd)
        {
            timeStart = Convert.ToDateTime(time.ToString("yyyy-MM-dd 00:00:00"));
            timeEnd = Convert.ToDateTime(time.ToString("yyyy-MM-dd 23:59:59"));
        }

        public static void GetDateTimeStartAndEnd(ref DateTime timeStart, ref DateTime timeEnd)
        {
            timeStart = Convert.ToDateTime(timeStart.ToString("yyyy-MM-dd 00:00:00"));
            timeEnd = Convert.ToDateTime(timeEnd.ToString("yyyy-MM-dd 23:59:59"));
        }

        public static string GetGuid(string guid)
        {
            return String.IsNullOrEmpty(guid) ? Guid.NewGuid().ToString().Replace("-", "") : guid;
        }


        public static string CheckObjectNull<T>(T value)
        {
            string s = Convert.ToString(value);
            return String.IsNullOrEmpty(s) ? String.Empty : s;
        }

        public static decimal CheckDecimalNull(object value)
        {
            return value == DBNull.Value ? 0 : Convert.ToDecimal(value);
        }

        public static double CheckDoubleNull(object value)
        {
            return value == DBNull.Value ? 0 : Convert.ToDouble(value);
        }

        public static int CheckIntNull(object value)
        {
            return value == DBNull.Value ? 0 : Convert.ToInt32(value);
        }

        public static char CheckCharNull(object value)
        {
            return value == DBNull.Value ? ' ' : Convert.ToChar(value);
        }

        public static string GetTimeString(DateTime? value)
        {
            return value == null ? "" : value.Value.ToString(DateTimeConst.DisplayLongDate);
        }


        public static DateTime CheckDatetimeNull(object value)
        {
            if (value == DBNull.Value)
            {
                return DateTime.Now;
            }
            else
            {
                DateTime mytime;
                try
                {
                    mytime = Convert.ToDateTime(value);
                }
                catch (Exception)
                {
                    mytime = new DateTime(1900, 1, 1);
                }

                return mytime;
            }
        }

        public static DateTime CheckDatetimeNull(object value, DateTime defaultValue)
        {
            if (value == DBNull.Value)
            {
                return DateTime.Now;
            }
            else
            {
                DateTime mytime;
                try
                {
                    mytime = Convert.ToDateTime(value);
                }
                catch (Exception)
                {
                    mytime = defaultValue;
                }

                return mytime;
            }
        }

        public static byte[] CheckByteNull(object value)
        {
            var buffer = new byte[0];

            if (value != DBNull.Value)
            {
                try
                {
                    buffer = (byte[])value;
                }
                catch
                {
                    buffer = new byte[0];
                }
            }

            return buffer;
        }


        public static DateTime CheckDatetimeIfNullThanMin(object value)
        {
            if (value == DBNull.Value)
            {
                return DateTime.MinValue;
            }
            else
            {
                DateTime mytime;
                try
                {
                    mytime = Convert.ToDateTime(value);
                }
                catch (Exception)
                {
                    mytime = new DateTime(1900, 1, 1);
                }

                return mytime;
            }
        }

        public static double MaxValue = 9999999999.99;
        public static double MinValue = -9999999999.99;

        public static double CheckMaxAndMin(double input)
        {
            if (input >= 0)
            {
                return input >= MaxValue ? MaxValue : input;
            }

            return input <= MinValue ? MinValue : input;
        }

        public static double CheckDoubleMaxMinNull(object value)
        {
            return value == DBNull.Value ? 0 : CheckMaxAndMin(Convert.ToDouble(value));
        }

        //public static <T> TosTrings(T value)
        //{
        //    return value == DBNull.Value ? 0 : CheckMaxAndMin(Convert.ToDouble(value));
        //}
    }
}
